package com.dikeleakagedetection.myapplication.ui.ble


import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.clj.fastble.BleManager
import com.clj.fastble.data.BleDevice
import com.dikeleakagedetection.myapplication.databinding.FragBleServiceBinding

class ServiceFragment : Fragment() {

    companion object {
        private const val KEY_DATA_1 = "key_ble_device"

        fun newInstance(bleDevice: BleDevice): ServiceFragment {
            val serviceFragment = ServiceFragment()
            //使用Bundle封装数据
            val bundle = Bundle()
            bundle.putParcelable(KEY_DATA_1, bleDevice as Parcelable)
            serviceFragment.arguments = bundle
            //即使fragment重构，也会通过反射的机制，把重新实例化的fragment设上参数title
            return serviceFragment
        }
    }

    private lateinit var binding: FragBleServiceBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragBleServiceBinding.inflate(inflater, container, false)
        val view = binding.root

        val bleDevice: BleDevice? = arguments?.getParcelable(KEY_DATA_1)

        val gatt = BleManager.getInstance().getBluetoothGatt(bleDevice)
        val serviceList = gatt.services

        binding.tbFragBleService.apply {
            title = bleDevice?.name
            subtitle = bleDevice?.mac
        }


        val linearLayoutManager = LinearLayoutManager(context)
        val serviceAdapter = ServiceAdapter(this.requireContext(), serviceList, bleDevice!!)
        binding.rvServicesFragBleService.apply {
            layoutManager = linearLayoutManager
            adapter = serviceAdapter
            addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
        }

        return view
    }

}